package com.wx.house.terminal.api.client.service.impl;

import com.wx.house.common.assembly.alyidcard.IDCardUtil;
import com.wx.house.common.base.ProjectConfiguration;
import com.wx.house.common.exception.BusinessException;
import com.wx.house.common.exception.UserException;
import com.wx.house.common.util.StringUtil;
import com.wx.house.core.mapper.fileupload.AttaUploadMapper;
import com.wx.house.core.mapper.tenant.TUserMapper;
import com.wx.house.core.mapper.tenant.UserCustomMapper;
import com.wx.house.core.pojo.dto.tenant.IdCardValidDto;
import com.wx.house.core.pojo.po.TUser;
import com.wx.house.core.pojo.vo.TUserContractVo;
import com.wx.house.core.pojo.vo.TUserIDCardVo;
import com.wx.house.terminal.api.client.service.UserService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @Author ：罗棋
 * @Email ：58428467@qq.com
 * @date ：Created in 2019/11/26 上午 10:37
 * @description：
 * @version: ：V
 */
@Service
@RequiredArgsConstructor
public class UserServiceImpl implements UserService {
private final UserCustomMapper userCustomMapper;
private final TUserMapper tUserMapper;
private final IDCardUtil idCardUtil;
private final AttaUploadMapper attaUploadMapper;
private final ProjectConfiguration projectConfiguration;

@Override
public TUserIDCardVo selectTUserIDCardVo(String userId) {
	TUserIDCardVo tUserIDCardVo = userCustomMapper.selectTUserIDCardVo(userId);
	if (tUserIDCardVo == null) return null;
	if (StringUtil.isNotEmpty(tUserIDCardVo.getIdCardNumber())) {
		String staticResourceUrl = projectConfiguration.getStaticResource().getStaticResourceUrl();
		tUserIDCardVo.setIdCard(staticResourceUrl + tUserIDCardVo.getIdCard());
		tUserIDCardVo.setIdCard_r(staticResourceUrl + tUserIDCardVo.getIdCard_r());
	} else return null;
	return userCustomMapper.selectTUserIDCardVo(userId);
}


@Override
public void updateUserIdCard(IdCardValidDto idCardValidDto, String userId) {
	//检查实名信息
	idCardUtil.validated(idCardValidDto.getIdCardNumber(), idCardValidDto.getName());
	
	//检查是否实名
	TUser tUser = tUserMapper.selectById(userId);
	if (StringUtil.isNotEmpty(tUser.getIdCardNumber())) {
		 throw new UserException("实名认证已经通过，无需重复认证", 201);
	}
	
	//更新实名信息
	tUserMapper.updateById(
			TUser.builder()
					.name(idCardValidDto.getName())
					.idCardNumber(idCardValidDto.getIdCardNumber())
					.idCardType(1)
					.build(),
			userId);
	
	//更新身份证图片
	List<String> fileIdList = new ArrayList<>();
	fileIdList.add(idCardValidDto.getIdCard());
	fileIdList.add(idCardValidDto.getIdCard_r());
	attaUploadMapper.updateResourceIdByIdIn(userId, fileIdList);
}


@Override
public TUserContractVo selectTenantContractDetail(String contractId) {
	return userCustomMapper.selectTenantContractDetail(contractId);
}
}
